package com.iweb.tmall.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.iweb.tmall.entity.Admin;
import com.iweb.tmall.global.ErrorEnum;
import com.iweb.tmall.global.ResponseData;
import com.iweb.tmall.mapper.AdminMapper;
import com.iweb.tmall.param.AdminParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseData getList(AdminParam param) {
        return null;
    }

    @Override
    public ResponseData deleteById(Integer id) {
        ResponseData responseData = null;
        Admin admin = new Admin();
        admin.setId(id);
        admin.setIsDelete("1");
        int row = adminMapper.updateById(admin);
        if (row > 0){
            responseData = new ResponseData("删除成功");
        }else {
            responseData = new ResponseData(ErrorEnum.DATABASE_SERVICE_ERROR);
        }

        return responseData;
    }

    @Override
    public ResponseData updateById(Admin entity) {
        ResponseData responseData = null;
        int row = adminMapper.updateById(entity);
        if (row > 0){
            responseData = new ResponseData(entity);
        }else {
            responseData = new ResponseData(ErrorEnum.DATABASE_SERVICE_ERROR);
        }

        return responseData;
    }

    @Override
    public ResponseData save(Admin entity) {
        ResponseData responseData = null;
        //调用mapper层插入管理员之前，先取出密码进行加密
        entity.setPassword(DigestUtils.md5Hex(entity.getPassword()));
        int row = adminMapper.insert(entity);
        if (row > 0) {
            responseData = new ResponseData(entity);
        }else {
            responseData = new ResponseData(ErrorEnum.DATABASE_SERVICE_ERROR);
        }
        return responseData;
    }

    @Override
    public ResponseData getById(Integer id) {
        return null;
    }

    @Override
    public ResponseData login2(Admin admin,HttpServletRequest request, HttpServletResponse response) {
        ResponseData responseData = null;
        Integer row = adminMapper.validAuth(admin.getUsername(), DigestUtils.md5Hex(admin.getPassword()));
        if (row == 1){
            String auth = System.currentTimeMillis()+ UUID.randomUUID().toString();
            Cookie cookie = new Cookie("Auth",auth);
            cookie.setPath("/");
            cookie.setMaxAge(60*30);
            response.addCookie(cookie);
            HttpSession session = request.getSession();
            session.setAttribute("Auth",auth);
            admin.setToken(auth);
            responseData = new ResponseData(admin);
        }else {
            responseData = new ResponseData(ErrorEnum.LOGIN_ERROR);
        }
        return responseData;
    }

    @Override
    public ResponseData login(Admin admin, HttpServletRequest request, HttpServletResponse response) {
        ResponseData responseData = null;
        LambdaQueryWrapper<Admin> qw = getLambdaQueryWrapper(admin)
                .eq(Admin::getUsername,admin.getUsername());
        Admin one = adminMapper.selectOne(qw);
        if (one != null){
            if (one.getPassword().equals(DigestUtils.md5Hex(admin.getPassword()))){
                String token = DigestUtils.md5Hex(UUID.randomUUID().toString());
                /*HttpSession session = request.getSession();
                session.setAttribute("Auth",token);*/
                //使用redis缓存服务器存储令牌，并设置过期时间
                stringRedisTemplate.opsForValue().set(token,token,60*60, TimeUnit.SECONDS);
                Cookie cookie = new Cookie("Auth",token);
                cookie.setPath("/");
                cookie.setMaxAge(60*30);
                response.addCookie(cookie);
                one.setToken(token);
                responseData = new ResponseData(one);

            }else {
                responseData = new ResponseData(ErrorEnum.PASSWORD_VERIFICATION_FAILD);
            }
        }else {
            responseData = new ResponseData(ErrorEnum.ACCOUNT_VERIFICATION_FAILD);
        }
        return responseData;




        /*ResponseData responseData = null;
*//*
        LambdaQueryWrapper<Admin> eq = new LambdaQueryWrapper<Admin>()
                .eq(Admin::getUsername, admin.getUsername());
*//*

        LambdaQueryWrapper<Admin> qw = getLambdaQueryWrapper(admin)
                .eq(Admin::getUsername, admin.getUsername());
        Admin one = adminMapper.selectOne(qw);
        if (one != null){
            if (one.getPassword().equals(DigestUtils.md5Hex(admin.getPassword()))){
                //用户存在且密码校验正确，颁发token身份令牌
                String token = DigestUtils.md5Hex(UUID.randomUUID().toString());
                //1.token缓存在本地session中
                HttpSession session = request.getSession();
                session.setAttribute("Auth",token);
                //2.token 缓存到cookie中，返回给浏览器
                Cookie cookie = new Cookie("Auth", token);
                cookie.setPath("/"); // 设置cookie的作用域, 在当前项目的根路径下所有地址中都可见
                cookie.setMaxAge(60*30); // 设置cookie的过期时间为30分钟
                response.addCookie(cookie);
                //3.cookie 作为报文一起返回给ajax,把token存到one对象中，把one对象存到ResponseData对象中进行返回
                one.setToken(token);
                responseData = new ResponseData(one);
            }else {
                responseData = new ResponseData(ErrorEnum.PASSWORD_VERIFICATION_FAILD);
            }
        }else {
            responseData = new ResponseData(ErrorEnum.ACCOUNT_VERIFICATION_FAILD);
        }
        return responseData;*/

    }
}
